<?php

namespace h5\controllers\base;

/**
 * H5的基类-需要验证权限
 *
 * @author peng.huang
 */
class H5AuthBaseController extends H5BaseController {

    /**
     * 初始化
     */
    public function init() {
        // 禁止缓存
        $this->response->setHeaders(
                array('Content-type' => 'text/html;charset=utf-8',
                    'Cache-Control' => 'no-cache, must-revalidate',
                    'Last-Modified' => gmdate('D, d M Y H:i:s') . ' GMT',
                    'Pragma' => 'no-cache',
                    'Expires' => -1
                )
        );

        // 加载公共的js和css
        //$this->addJs('web/js/jquery/jquery-2.1.1.min');
        //$this->addCss('web/css/c');
        $this->_checkIsLogged();
    }

    /**
     * 验证用户是否登录；没有登录则跳到首页
     */
    protected function _checkIsLogged() {
        $account = $this->readAccount();
        if (isset($account)) {
            return;
        }

        // 没有登录
        // ajax请求则输出json格式
        if ($this->request->isAjax()) {
            header('Content-type: application/json');
            echo json_encode(array('code' => 'login_out'));
            exit;
        } else {
            // 将当前URL加在returnurl参数中
            $returnUrl = $this->request->server('REQUEST_URI');
            if (isset($returnUrl[0])) {
                $returnUrl = '?returnurl=' . urlencode($returnUrl);
            }

            $this->response->redirect('/h5/login' . $returnUrl, 302);
        }
    }

}
